package controller;

import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import pojo.DoctorWork;
import service.DoctorWorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/doctor/work")
@Api(tags = "医生排班管理", description = "医生排班信息的增删改查及预约管理")
public class DoctorWorkController {

    @Autowired
    private DoctorWorkService doctorWorkService;

    // 基本CRUD接口
    @PostMapping("/add")
    @ApiOperation(value = "添加医生排班", notes = "创建新的医生排班记录")
    @ApiResponses({
            @ApiResponse(code = 201, message = "添加成功"),
            @ApiResponse(code = 400, message = "参数无效"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    public ResponseEntity<Void> addDoctorWork(@RequestBody @ApiParam(value = "医生排班信息", required = true) DoctorWork doctorWork) {
        int result = doctorWorkService.addDoctorWork(doctorWork);
        return result > 0 ?
                ResponseEntity.status(HttpStatus.CREATED).build() :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    @DeleteMapping("/delete/{day}/{docId}")
    @ApiOperation(value = "删除医生排班", notes = "根据日期和医生ID删除排班记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "排班日期 (格式: yyyy-MM-dd)", paramType = "path", required = true),
            @ApiImplicitParam(name = "docId", value = "医生ID", paramType = "path", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 204, message = "删除成功"),
            @ApiResponse(code = 404, message = "记录不存在"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    public ResponseEntity<Void> deleteDoctorWork(@PathVariable String day, @PathVariable String docId) {
        int result = doctorWorkService.deleteDoctorWork(day, docId);
        return result > 0 ?
                ResponseEntity.noContent().build() :
                ResponseEntity.notFound().build();
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新医生排班", notes = "根据传入的排班信息进行更新")
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 400, message = "参数无效"),
            @ApiResponse(code = 404, message = "记录不存在"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    public ResponseEntity<Void> updateDoctorWork(@RequestBody @ApiParam(value = "医生排班信息", required = true) DoctorWork doctorWork) {
        int result = doctorWorkService.updateDoctorWork(doctorWork);
        return result > 0 ?
                ResponseEntity.ok().build() :
                ResponseEntity.notFound().build();
    }

    @GetMapping("/{day}/{docId}")
    @ApiOperation(value = "获取单个排班记录", notes = "根据日期和医生ID查询排班详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "排班日期 (格式: yyyy-MM-dd)", paramType = "path", required = true),
            @ApiImplicitParam(name = "docId", value = "医生ID", paramType = "path", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = DoctorWork.class),
            @ApiResponse(code = 404, message = "记录不存在")
    })
    public ResponseEntity<DoctorWork> getDoctorWorkByDayAndDocId(@PathVariable String day, @PathVariable String docId) {
        DoctorWork work = doctorWorkService.getDoctorWorkByDayAndDocId(day, docId);
        return work != null ?
                ResponseEntity.ok(work) :
                ResponseEntity.notFound().build();
    }

    @GetMapping("/doctor/{docId}")
    @ApiOperation(value = "获取医生所有排班", notes = "查询指定医生的所有排班记录")
    @ApiImplicitParam(name = "docId", value = "医生ID", paramType = "path", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = DoctorWork.class, responseContainer = "List"),
            @ApiResponse(code = 404, message = "记录不存在")
    })
    public ResponseEntity<List<DoctorWork>> getDoctorWorksByDocId(@PathVariable String docId) {
        List<DoctorWork> works = doctorWorkService.getDoctorWorksByDocId(docId);
        return !works.isEmpty() ?
                ResponseEntity.ok(works) :
                ResponseEntity.notFound().build();
    }

    @GetMapping("/day/{day}")
    @ApiOperation(value = "获取指定日期所有排班", notes = "查询指定日期的所有医生排班")
    @ApiImplicitParam(name = "day", value = "排班日期 (格式: yyyy-MM-dd)", paramType = "path", required = true)
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = DoctorWork.class, responseContainer = "List"),
            @ApiResponse(code = 404, message = "记录不存在")
    })
    public ResponseEntity<List<DoctorWork>> getDoctorWorksByDay(@PathVariable String day) {
        List<DoctorWork> works = doctorWorkService.getDoctorWorksByDay(day);
        return !works.isEmpty() ?
                ResponseEntity.ok(works) :
                ResponseEntity.notFound().build();
    }

    @GetMapping("/all")
    @ApiOperation(value = "获取所有排班记录", notes = "查询系统中所有医生的排班信息")
    @ApiResponse(code = 200, message = "查询成功", response = DoctorWork.class, responseContainer = "List")
    public ResponseEntity<List<DoctorWork>> getAllDoctorWorks() {
        return ResponseEntity.ok(doctorWorkService.getAllDoctorWorks());
    }

    // 订单数量相关接口
    @GetMapping("/count/{day}/{docId}")
    @ApiOperation(value = "获取排班号源信息", notes = "查询指定排班的剩余号源和已预约数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "排班日期 (格式: yyyy-MM-dd)", paramType = "path", required = true),
            @ApiImplicitParam(name = "docId", value = "医生ID", paramType = "path", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = Map.class),
            @ApiResponse(code = 404, message = "排班记录不存在")
    })
    public ResponseEntity<Map<String, Object>> getCount(@PathVariable String day, @PathVariable String docId) {
        DoctorWork work = doctorWorkService.getDoctorWorkCount(day, docId);
        if (work != null) {
            Map<String, Object> result = new HashMap<>();
            result.put("countLeft", work.getCountLeft());
            result.put("orderedCount", work.getOrderedCount() != null ? work.getOrderedCount() : 0);
            result.put("success", true);
            return ResponseEntity.ok(result);
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "未找到排班记录");
            result.put("success", false);
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
        }
    }

    @PutMapping("/count/update")
    @ApiOperation(value = "更新剩余号源数量", notes = "修改指定排班的剩余号源数量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "排班日期 (格式: yyyy-MM-dd)", paramType = "query", required = true),
            @ApiImplicitParam(name = "docId", value = "医生ID", paramType = "query", required = true),
            @ApiImplicitParam(name = "countLeft", value = "剩余号源数量", paramType = "query", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 400, message = "参数无效"),
            @ApiResponse(code = 404, message = "记录不存在"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    public ResponseEntity<Void> updateCountLeft(@RequestParam String day,
                                                @RequestParam String docId,
                                                @RequestParam Integer countLeft) {
        boolean result = doctorWorkService.updateCountLeft(day, docId, countLeft);
        return result ?
                ResponseEntity.ok().build() :
                ResponseEntity.notFound().build();
    }

    @PostMapping("/book")
    @ApiOperation(value = "预约挂号", notes = "为指定排班创建预约")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "排班日期 (格式: yyyy-MM-dd)", paramType = "query", required = true),
            @ApiImplicitParam(name = "docId", value = "医生ID", paramType = "query", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "预约成功"),
            @ApiResponse(code = 400, message = "参数无效"),
            @ApiResponse(code = 404, message = "排班不存在"),
            @ApiResponse(code = 409, message = "号源不足"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    public ResponseEntity<Void> bookAppointment(@RequestParam String day, @RequestParam String docId) {
        boolean result = doctorWorkService.bookAppointment(day, docId);
        return result ?
                ResponseEntity.ok().build() :
                ResponseEntity.status(HttpStatus.CONFLICT).build();
    }

    @PostMapping("/cancel")
    @ApiOperation(value = "取消预约", notes = "取消指定排班的预约")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "排班日期 (格式: yyyy-MM-dd)", paramType = "query", required = true),
            @ApiImplicitParam(name = "docId", value = "医生ID", paramType = "query", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "取消成功"),
            @ApiResponse(code = 400, message = "参数无效"),
            @ApiResponse(code = 404, message = "排班不存在或无预约记录"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    public ResponseEntity<Void> cancelAppointment(@RequestParam String day, @RequestParam String docId) {
        boolean result = doctorWorkService.cancelAppointment(day, docId);
        return result ?
                ResponseEntity.ok().build() :
                ResponseEntity.notFound().build();
    }

    @GetMapping("/department/parent/{deptId}") // 修改路径变量名，使其和方法参数名一样
    @ApiOperation(value = "根据父级部门ID查询医生排班", notes = "查询指定父级部门下所有医生的排班信息")
    @ApiImplicitParam(name = "deptId", value = "父级部门ID", paramType = "path", required = true) // 修改参数名
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = DoctorWork.class, responseContainer = "List"),
            @ApiResponse(code = 404, message = "记录不存在")
    })
    public ResponseEntity<List<DoctorWork>> getDoctorWorksByParentDeptId(@PathVariable Integer deptId) {
        System.out.println("接收到的deptId: " + deptId);
        List<DoctorWork> works = doctorWorkService.getDoctorWorksByParentDeptId(deptId);
        return !works.isEmpty() ?
                ResponseEntity.ok(works) :
                ResponseEntity.notFound().build();
    }
}